﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using My.Pattern.Factory;
using My.Web.MVC.V4.Factory;
using NCLCustomerManagement.BusinessLogic.Category;
using NCLCustomerManagement.BusinessLogic.Products;
using NCLCustomerManagement.Common.Constant;
using NCLCustomerManagement.DataTransferObjects.Customer;
using NCLCustomerManagement.DataTransferObjects.Product;
using NCLCustomerManagement.UI.Controllers;
using NCLCustomerManagement.UI.Models;
using NCLCustomerManagement.UI.Models.Customer;
using NCLCustomerManagement.UI.Models.ProductCategory;
using NCLCustomerManagement.UI.Models.User;


namespace NCLCustomerManagement.UI.Controllers
{
    public static class HomeControllerExtensions
    {
        public static string RegionCodeToString(this HomeController controller, Region region)
        {
            switch (region)
            {
                case Region.North: return "Bắc";
                case Region.Middle: return "Trung";
                case Region.South: return "Nam";
                default: return "None";
            }
        }

        public static string[] CreateRowsJson(this HomeController controller, CustomerModel customer)
        {
            List<string> result = new List<string>();

            result.Add("False");
            result.Add(customer.Id.ToString());
            result.Add(customer.Phone);
            result.Add(customer.CustomerName);
            result.Add(customer.Address);
            result.Add(customer.Notes);

            //result.Add(customer.Bank);
            //result.Add(customer.CreditCardNumber);
            //result.Add(string.Join(", ", customer.Products.Select(e => e.ProductCategoryName).ToArray()));
            result.Add(RegionCodeToString(controller, customer.CustomerRegion));
            result.Add(string.Format("{0} bởi {1}", string.Format("{0:dd/MM/yyyy}", customer.LastModifiedDate), customer.LastModifiedUser));

            return result.ToArray();
        }

        public static void SetupCategoryListForDropdown(this HomeController controller, ICustomerBC bc)
        {
            var cates = GetAllCategories(controller, bc).ToList();
            cates.Insert(0, new ProductCategoryModel() { Id = -1, ProductCategoryName = "Tất cả sản phẩm" });
            var cateSelectList = new SelectList(cates, "Id", "ProductCategoryName", -1);
            controller.ViewBag.CategorySelectList = cateSelectList;
        }

        public static void SetupCategoryListForAllItemsListBox(this HomeController controller, ICustomerBC bc)
        {
            var cates = GetAllCategories(controller, bc);
            var cateSelectList = new SelectList(cates, "Id", "ProductCategoryName");
            controller.ViewBag.CategorySelectListForAllItemsListBox = cateSelectList;

        }
        public static IEnumerable<ProductCategoryModel> GetAllCategories(this BaseController controller, ICustomerBC bc)
        {
            List<ProductCategoryModel> cates = new List<ProductCategoryModel>() { };
            cates.AddRange(bc.GetAllCategories()
                .Select(e => controller.ConvertDTOToModel<ProductCategoryDTO, ProductCategoryModel>(e))
                .ToList());
            return cates;
        }

        public static IEnumerable<ProductModel> GetAllProducts(this BaseController controller, IProductBC bc)
        {
            return bc.GetAllProducts()
                .Select(e => controller.ConvertDTOToModel<ProductDTO, ProductModel>(e))
                .ToList();
        }

        public static string RepresentTime(this BaseController controller, double dayCount)
        {
            float day;
            int month, year;

            ComputeTime(dayCount, out day, out month, out year);
            var str = string.Format("{0}{1}{2}", year > 0 ? year.ToString() + " năm " : "",
                month > 0 ? month.ToString() + " tháng " : "",
                day.ToString() + " ngày");
            return str;
        }
        private static void ComputeTime(double dayCount, out float day, out int month, out int year)
        {
            year = (int)(dayCount / 360.0);
            month = (int)((dayCount % 360) / 30.0);
            day = (int)(dayCount % 360) % 30;
        }

        public static IEnumerable<CustomerModel> GetAllCustomers(this BaseController controller, ICustomerBC bc)
        {
            return bc.GetAllCustomers()
                .Select(e => controller.ConvertDTOToModel<CustomerDTO, CustomerModel>(e))
                .ToList();
        }
        public static IEnumerable<SelectListItem> SetupRegion(this HomeController controller, Region region)
        {
            yield return new SelectListItem() { Text = "Miền Bắc", Value = "0", Selected = (region == Region.North) };
            yield return new SelectListItem() { Text = "Miền Trung", Value = "1", Selected = (region == Region.Middle) };
            yield return new SelectListItem() { Text = "Miền Nam", Value = "2", Selected = (region == Region.South) };
        }

        public static IEnumerable<SelectListItem> SetupRegion(this HomeController controller)
        {
            yield return new SelectListItem() { Text = "Miền Bắc", Value = "0", Selected = true };
            yield return new SelectListItem() { Text = "Miền Trung", Value = "1" };
            yield return new SelectListItem() { Text = "Miền Nam", Value = "2" };
        }
    }

    public static class ControllerExtentions
    {
        public static AuthenticatedUser GetCurrentUser(this Controller controller)
        {
            return controller.Session[Constant.CURRENT_USER] as AuthenticatedUser;
        }
    }

    public static class UserControllerExtensions
    {
        public static void SaveUserInSession(this UserController controller, string username, bool isAdmin, string manager)
        {
            var currentUser = new AuthenticatedUser() { Username = username, IsAdmin = isAdmin, Manager = manager };
            controller.Session[Constant.CURRENT_USER] = currentUser;
        }

        public static void ClearCurrentUser(this UserController controller)
        {
            controller.Session.Abandon();
        }

        public static string[] CreateUserListJson(this UserController controller, UserProfileModel model)
        {
            List<string> result = new List<string>();

            result.Add("False");
            result.Add(model.Username);
            result.Add(model.Username);
            result.Add(model.Email);
            result.Add(model.Active ? "Đang hoạt động" : "Không hoạt động");

            return result.ToArray();
        }

        public static string GenerateInitialPassword(this UserController controller)
        {
            return System.Web.Security.Membership.GeneratePassword(8, 2);
        }
    }

    public static class SaleControllerExtentions
    {
        public static string[] CreateSaleListJson(this SaleController controller, SaleModel model)
        {
            List<string> result = new List<string>();

            result.Add("False");
            result.Add(model.Id.ToString());
            result.Add(model.SaleDate.ToString("dd/MM/yyyy"));
            result.Add(model.CustomerName);
            result.Add(model.ProductName);
            result.Add(model.Unit);
            result.Add(model.Quantity.ToString());
            result.Add(model.UnitPrice.ToString("#,##0.00"));
            result.Add(model.Tax.ToString("#,##0.00"));
            result.Add(model.Discount.ToString("#,##0.00"));
            result.Add(model.TotalValue.ToString("#,##0.00"));

            //var remainingDays =model.ExpireUsedDate.Subtract(DateTime.Now.Date).TotalDays;
            //var remainingUseTime = controller.RepresentTime(remainingDays);
            //result.Add(remainingUseTime);
            result.Add(model.ExpireUsedDate.ToString("dd/MM/yyyy"));
            result.Add(model.CreatedBy);
            return result.ToArray();
        }
    }
}